using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;

namespace nToolbox.Data.SQLServer
{
	/// <summary>
	/// Enumerates available instances of SQL Server
	/// </summary>
	/// <remarks>
	/// The built in enumerator (System.Data.Sql.SqlDataSourceEnumerator) returns a DataTable 
	/// which to me is awkward to work with.
	/// </remarks>
	public class SQLServerHelper
	{
		public static IList<SQLServerInformation> EnumerateInstances()
		{
			List<SQLServerInformation> results = new List<SQLServerInformation>();
			DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();

			if (dt != null && dt.Rows.Count > 0)
			{
				foreach (DataRow item in dt.Rows)
				{
					SQLServerInformation instance = new SQLServerInformation();
					instance.InstanceName = GetString(item, "InstanceName");
					instance.IsClustered = GetBoolean(item, "IsClustered");
					instance.ServerName = GetString(item, "ServerName");
					instance.Version = GetString(item, "Version");

					results.Add(instance);
				}
			}
			return results;
		}


		/// <summary>
		/// Gets a string value from a column in data row
		/// </summary>
		/// <remarks>
		/// TODO: Add SafeDataReader
		/// </remarks>
		private static string GetString(DataRow dr, string columnName)
		{
			if (dr.IsNull(columnName))
			{
				return String.Empty;
			}
			else
			{
				return dr[columnName].ToString();
			}
		}

		/// <summary>
		/// Gets a boolean value from a column in data row
		/// </summary>
		/// <remarks>
		/// TODO: Add SafeDataReader
		/// </remarks>
		private static bool GetBoolean(DataRow dr, string columnName)
		{
			if (dr.IsNull(columnName))
			{
				return false;
			}
			else
			{
				bool value;
				bool.TryParse(dr[columnName].ToString(), out value);
				return value;
			}
		}
	}
}